package com.example.demo.service;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionalInvocationHandler implements InvocationHandler {

    private Object target;
    private TransactionManager transactionManager;


    public TransactionalInvocationHandler(Object target, TransactionManager transactionManager) {
        this.target = target;
        this.transactionManager = transactionManager;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        Connection connection = null;
        try {

            BasicDataSource dataSource = new BasicDataSource();

            connection = dataSource.getConnection();

            // 开启事务
            transactionManager.beginTransaction();

            // 执行业务逻辑
            result = method.invoke(target, args);

            // 提交事务
            transactionManager.commitTransaction();
        } catch (SQLException e) {
            e.printStackTrace();

            // 回滚事务
            transactionManager.rollbackTransaction();
        } finally {
            // 关闭连接
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }
}
